/**
 * Activity Main.
 *
 * Released under Apache License, Version 2.0.
 */

package bsp.eclair.simplelinechart;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ActivityMain extends Activity implements OnClickListener
{
	protected Button btnAddData, btnContinuous, btnExit;
	protected SimpleLineChartViewWorking viewLineChartWorking;
	protected SimpleLineChartViewQ1 viewLineChartQ1;
	protected SimpleLineChartViewQ4 viewLineChartQ4;
	protected float x;
	protected ApplicationAsyncTask mApplicationAsyncTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btnExit = (Button)findViewById(R.id.btnExit);
		btnExit.setOnClickListener(this);
		
		btnAddData = (Button)findViewById(R.id.btnAddData);
		btnAddData.setOnClickListener(this);
		
		btnContinuous = (Button)findViewById(R.id.btnContinuous);
		btnContinuous.setOnClickListener(this);
		
		viewLineChartWorking = (SimpleLineChartViewWorking)findViewById(R.id.viewSimpleLineChartWorking);
		viewLineChartWorking.setParentActivity(this);
		viewLineChartQ1 = (SimpleLineChartViewQ1)findViewById(R.id.viewSimpleLineChartQ1);
		viewLineChartQ1.setParentActivity(this);
		viewLineChartQ4 = (SimpleLineChartViewQ4)findViewById(R.id.viewSimpleLineChartQ4);
		viewLineChartQ4.setParentActivity(this);
		
		x = 0.0f;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onClick(View v)
	{
		if ( v == btnExit ) {
			mApplicationAsyncTask.setRunning(false);
			mApplicationAsyncTask.cancel(true);
			mApplicationAsyncTask = null;
			
			finish();
		} else if ( v == btnAddData ) {
			addData();
			
			// refresh all views
			refresh();
		} else if ( v == btnContinuous ) {
			mApplicationAsyncTask = new ApplicationAsyncTask(this);
			if ( mApplicationAsyncTask != null ) {
				mApplicationAsyncTask.setRunning(true);
				mApplicationAsyncTask.execute();
			}
		}
	}
	
	public void addData()
	{
		float y = (float) Math.random();
		
		if ( x > 0.5 ) {
			viewLineChartWorking.getViewWorld().updateWorldDimensionsByOffset(0.1f,  0);
			viewLineChartQ1.getViewWorld().updateWorldDimensionsByOffset(0.1f,  0);
			viewLineChartQ4.getViewWorld().updateWorldDimensionsByOffset(0.1f,  0);
		}

		x += 0.1;
		
		// add data
		viewLineChartWorking.addData(x, y);
		// add data
		viewLineChartQ1.addData(x, y);
		// add data
		viewLineChartQ4.addData(x, y);
	}
	
	public void refresh()
	{
		viewLineChartWorking.invalidate();
		viewLineChartQ1.invalidate();
		viewLineChartQ4.invalidate();
	}
}

/* end */
